package handler

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func FoodAdd(c *gin.Context) {
	food_name := c.PostForm("food_name")
	price, _ := strconv.Atoi(c.PostForm("price"))
	data := model.Food{
		FoodName: food_name,
		Price:    price,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "创建成功",
	})
	return

}
func FoodList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	model.DB.Model(&model.Food{}).Count(&total)

	var data []model.Food
	redis_key := "food_list_" + strconv.Itoa(int(page))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
	return
}
func FoodSearch(c *gin.Context) {
	id := c.Query("id")
	var data model.Food
	redis_key := "food_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Model(&model.Food{}).Where("id=?", id).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"data": data,
	})
	return
}
